package com.atguigu.srb.sms.service.impl;

import com.atguigu.common.exception.BusinessException;
import com.atguigu.common.result.ResponseEnum;
import com.atguigu.srb.sms.service.SmsService;
import com.atguigu.srb.sms.util.SmsProperties;

import darabonba.core.exception.ClientException;
import darabonba.core.exception.ServerException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.core.http.HttpClient;
import com.aliyun.core.http.HttpMethod;
import com.aliyun.core.http.ProxyOptions;
import com.aliyun.httpcomponent.httpclient.ApacheAsyncHttpClientBuilder;
import com.aliyun.sdk.service.dysmsapi20170525.models.*;
import com.aliyun.sdk.service.dysmsapi20170525.*;
import com.google.gson.Gson;
import darabonba.core.RequestConfiguration;
import darabonba.core.client.ClientOverrideConfiguration;
import darabonba.core.utils.CommonUtil;
import darabonba.core.TeaPair;

//import javax.net.ssl.KeyManager;
//import javax.net.ssl.X509TrustManager;
import java.net.InetSocketAddress;

import java.time.Duration;
import java.util.*;
import java.util.concurrent.CompletableFuture;


import java.util.Map;
import java.util.concurrent.ExecutionException;

@Service
@Slf4j
public class SmsServiceImpl implements SmsService {
    @Override
    public void send(String mobile, String templateCode, Map<String, Object> param) {

        // 配置凭据认证信息，包括ak、secret、token
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(SmsProperties.KEY_ID)
                .accessKeySecret(SmsProperties.KEY_SECRET)
                //.securityToken("<your-token>") // 使用STS令牌
                .build());

        // 配置客户端
        AsyncClient client = AsyncClient.builder()
                .region(SmsProperties.REGION_Id) // Region ID
                //.httpClient(httpClient) // 使用已配置的HttpClient，否则使用默认的HttpClient (Apache HttpClient)
                .credentialsProvider(provider)
                //.serviceConfiguration(Configuration.create()) // 服务级别配置
                // 客户端级配置重写，可以设置端点，Http请求参数等。
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                .setEndpointOverride("dysmsapi.aliyuncs.com")
                        //.setConnectTimeout(Duration.ofSeconds(30))
                )
                .build();

        // API请求参数设置
        Gson gson = new Gson();
        String json = gson.toJson(param);
        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .signName(SmsProperties.SIGN_NAME)
                .templateCode(templateCode)
                .phoneNumbers(mobile)
                .templateParam(json)
                // 请求级配置重写，可以设置Http请求参数等。
                // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
                .build();

        try {
            // 异步获取API请求的返回值
            CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);

            // 同步获取API请求的返回值
            SendSmsResponse resp = response.get();
            log.info("短信请求响应值：" + new Gson().toJson(resp));
        } catch (InterruptedException | ExecutionException e) {
            log.error("阿里云短信发送SDK调用失败：");
            log.error("ErrorMessage=" + e.getMessage());
            throw new BusinessException(ResponseEnum.ALIYUN_SMS_ERROR , e);
        } finally {
            client.close();
        }
    }
}
